package net.qqxh.resolve2text.impl;


import net.qqxh.resolve2text.File2TextResolve;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class Xlsx2TextResolve implements File2TextResolve {
    private static String TYPE = "xlsx";

    @Override
    public String resolve(File file) throws IOException {
        InputStream is = null;
        XSSFWorkbook workBook = null;
        String text = "";
        XSSFExcelExtractor extractor = null;
        try {
            is = new FileInputStream(file);
            workBook = new XSSFWorkbook(is);
            extractor = new XSSFExcelExtractor(workBook);
            extractor.setIncludeSheetNames(false);
            text = extractor.getText();
            extractor.close();
        } catch (IOException e) {
            throw e;
        } finally {
            if (extractor != null) {
                try {
                    extractor.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return text;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
